package com.jeesuite.admin.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.jeesuite.admin.exception.JeesuiteBaseException;
import com.jeesuite.admin.model.Constants;
import com.jeesuite.admin.model.LoginUserInfo;

public class SecurityUtil {
	
	public static enum Scope{
		READ,WRITE 
	}

	public static LoginUserInfo getLoginUserInfo(){
		 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return (LoginUserInfo) request.getSession().getAttribute(Constants.LOGIN_SESSION_KEY);
	}
	
	public static boolean isSuperAdmin(){
		LoginUserInfo userInfo = getLoginUserInfo();
		return userInfo != null && userInfo.isSuperAdmin();
	}
	
	public static void requireSuperAdmin(){
		if(!isSuperAdmin())throw new JeesuiteBaseException(403, "超级管理员才有权限操作");
	}
	
	public static void requireProfileGanted(String profile,Scope scope){
		if(StringUtils.isBlank(profile))throw new JeesuiteBaseException(1001, "profile字段缺失");
		LoginUserInfo userInfo = getLoginUserInfo();
		if(userInfo.isSuperAdmin())return;
		boolean authed = false;
		if(scope.equals(Scope.WRITE)){
			authed = userInfo.getGantProfiles().contains(profile);
		}else{			
			for (String auth : userInfo.getGantProfiles()) {
				if(authed = auth.contains(profile)){
					break;
				}
			}
		}
		if(!authed){
			throw new JeesuiteBaseException(403, "你没有profile["+profile+"]["+scope.name()+"]权限");
		}
	}
}
